package com.jzo2o.foundations.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.foundations.enums.FoundationStatusEnum;
import com.jzo2o.foundations.mapper.RegionMapper;
import com.jzo2o.foundations.mapper.ServeItemMapper;
import com.jzo2o.foundations.mapper.ServeMapper;
import com.jzo2o.foundations.model.domain.Region;
import com.jzo2o.foundations.model.domain.Serve;
import com.jzo2o.foundations.model.domain.ServeItem;
import com.jzo2o.foundations.model.dto.request.ServePageQueryReqDTO;
import com.jzo2o.foundations.model.dto.request.ServeUpsertReqDTO;
import com.jzo2o.foundations.model.dto.response.ServeAggregationSimpleResDTO;
import com.jzo2o.foundations.model.dto.response.ServeAggregationTypeSimpleResDTO;
import com.jzo2o.foundations.model.dto.response.ServeResDTO;
import com.jzo2o.foundations.service.IHomeService;
import com.jzo2o.foundations.service.IServerService;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class ServerServiceImpl extends ServiceImpl<ServeMapper, Serve> implements IServerService{
    @Override
    public PageResult<ServeResDTO> page(ServePageQueryReqDTO servePageQueryReqDTO) {
        PageResult<ServeResDTO> pageResult=PageHelperUtils.selectPage(servePageQueryReqDTO,
                () -> baseMapper.queryServeListByRegionId(servePageQueryReqDTO.getRegionId()));
        return pageResult;
    }

    @Resource
    private ServeItemMapper serveItemMapper;
    @Resource
    private RegionMapper regionMapper;

    @Override
    @Transactional
    public void batchAdd(List<ServeUpsertReqDTO> serveUpsertReqDTOList) {
        //遍历转入的参数
        for (ServeUpsertReqDTO serveUpsertReqDTO : serveUpsertReqDTOList) {
            //校验服务项是否存在，校验服务状态是否是启用状态
            ServeItem serveItem = serveItemMapper.selectById(serveUpsertReqDTO.getServeItemId());
            if (ObjectUtils.isEmpty(serveItem) || serveItem.getActiveStatus()== FoundationStatusEnum.DISABLE.getStatus()){
                throw  new ForbiddenOperationException("该服务未启用无法添加到区域下使用");
            }
            //校验是否重复新增
            Integer count = lambdaQuery().eq(Serve::getRegionId, serveUpsertReqDTO.getRegionId())
                    .eq(Serve::getServeItemId, serveUpsertReqDTO.getServeItemId())
                    .count();
            if (count>0){
                 throw new ForbiddenOperationException(serveItem.getName()+"服务已存在");
            }
            //执行新增操作
            Serve serve = BeanUtil.toBean(serveUpsertReqDTO, Serve.class);
            Region region = regionMapper.selectById(serveUpsertReqDTO.getRegionId());
            serve.setCityCode(region.getCityCode());
            baseMapper.insert(serve);
        }
    }

    @Override
    public Serve updatePrice(Long id, BigDecimal price) {
        boolean flag = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getPrice, price)
                .update();
        if (!flag){
            throw new CommonException("修改服务价格失败");
        }
        return baseMapper.selectById(id);
    }

    @Override
    public void onSale(Long id) {
        //根据区域服务的id查询区域服务
        Serve serve = baseMapper.selectById(id);
        //判断区域服务是否存在，不存在直接返回
        if (ObjectUtils.isEmpty(serve)){
            throw new ForbiddenOperationException("服务不存在");
        }
        //判断服务状态是否为草稿状态或下架状态
        if (serve.getSaleStatus()!=FoundationStatusEnum.INIT.getStatus() && serve.getSaleStatus()!=FoundationStatusEnum.DISABLE.getStatus()){
            throw new ForbiddenOperationException("草稿状态或下架状态可以上架");
        }
        //查询服务信息，判断是存在
        ServeItem serveItem = serveItemMapper.selectById(serve.getServeItemId());
        if (ObjectUtils.isEmpty(serveItem)){
            throw new ForbiddenOperationException("该服务不存在");
        }
        //判断状态
        if (serveItem.getActiveStatus()!=FoundationStatusEnum.ENABLE.getStatus()){
            throw new ForbiddenOperationException("该服务状态不是启用");
        }
        //执行修改数据库状态
        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getSaleStatus, FoundationStatusEnum.ENABLE.getStatus())
                .update();
        if (!update){
            throw new CommonException("区域服务上架失败");
        }
    }

    @Override
    public void offSale(Long id) {
        //根据区域服务的id查询区域服务
        Serve serve = baseMapper.selectById(id);
        //判断区域服务是否存在，不存在直接返回
        if (ObjectUtils.isEmpty(serve)){
            throw new ForbiddenOperationException("服务不存在");
        }
        //判断服务状态是否为启用状态
        if (serve.getSaleStatus()!=FoundationStatusEnum.ENABLE.getStatus()){
            throw new ForbiddenOperationException("启用状态可以下架");
        }
        //执行修改数据库状态
        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getSaleStatus, FoundationStatusEnum.DISABLE.getStatus())
                .update();
        if (!update){
            throw new CommonException("区域服务下架失败");
        }
    }

    @Override
    public void remove(Long id) {
        //根据区域服务的id查询区域服务
        Serve serve = baseMapper.selectById(id);
        //判断区域服务是否存在，不存在直接返回
        if (ObjectUtils.isEmpty(serve)){
            throw new ForbiddenOperationException("该区域服务不存在");
        }
        //判断服务状态是否为上架状态
        if (serve.getSaleStatus()!=FoundationStatusEnum.INIT.getStatus()){
            throw new ForbiddenOperationException("草稿状态可以删除");
        }
        //执行删除操作
        int delete = baseMapper.deleteById(id);
        if (delete<=0){
            throw new CommonException("区域服务删除失败");
        }
    }

    @Override
    public void onHot(Long id) {
        //根据区域服务的id查询区域服务
        Serve serve = baseMapper.selectById(id);
        //判断区域服务是否存在，不存在直接返回
        if (ObjectUtils.isEmpty(serve)){
            throw new ForbiddenOperationException("该区域服务不存在");
        }
        //判断服务状态是否为上架状态
        if (serve.getIsHot()==1){
            throw new ForbiddenOperationException("非热门状态才能设置热门");
        }
        //执行修改操作
        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getIsHot, 1)
                .update();
        if (!update){
            throw new CommonException("区域服务设置热门失败");
        }
    }

    @Override
    public void offHot(Long id) {
        //根据区域服务的id查询区域服务
        Serve serve = baseMapper.selectById(id);
        //判断区域服务是否存在，不存在直接返回
        if (ObjectUtils.isEmpty(serve)){
            throw new ForbiddenOperationException("该区域服务不存在");
        }
        //判断服务状态是否为上架状态
        if (serve.getIsHot()==0){
            throw new ForbiddenOperationException("热门状态才可以取消热门设置");
        }
        //执行修改操作
        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getIsHot, 0)
                .update();
        if (!update){
            throw new CommonException("区域服务取消热门失败");
        }
    }

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public void testRedis() {
        RLock rLock = redissonClient.getLock("mylock");
        try {
            boolean tryLock = rLock.tryLock(100, TimeUnit.SECONDS);
            if (tryLock){
                if (redisTemplate.opsForValue().get("num")==null){
                    redisTemplate.opsForValue().set("num",1L);
                }else {
                    Integer num = (Integer) redisTemplate.opsForValue().get("num");
                    redisTemplate.opsForValue().set("num",num+1);

                }
            }else {
                System.out.println("加锁失败");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            rLock.unlock();
        }
    }

    @Override
    public List<ServeAggregationTypeSimpleResDTO> findServeTypeListByRegionId(Long regionId) {
        return baseMapper.findServeTypeListByRegionId(regionId);
    }

    @Override
    public List<ServeAggregationSimpleResDTO> findHotServeListByRegionId(Long regionId) {
        return baseMapper.findHotServeListByRegionId(regionId);
    }

    @Resource
    IHomeService homeService;


    @Override
    public ServeAggregationSimpleResDTO findDetailById(Long id) {
        Serve serve=homeService.queryServeByIdCache(id);
        ServeItem serveItem=homeService.queryServeItemByIdCache(serve.getServeItemId());
        ServeAggregationSimpleResDTO serveAggregationSimpleResDTO = BeanUtil.toBean(serve, ServeAggregationSimpleResDTO.class);
        serveAggregationSimpleResDTO.setServeItemName(serveItem.getName());
        serveAggregationSimpleResDTO.setDetailImg(serveItem.getDetailImg());
        serveAggregationSimpleResDTO.setServeItemImg(serveItem.getImg());
        serveAggregationSimpleResDTO.setUnit(serveItem.getUnit());
        return serveAggregationSimpleResDTO;
    }


}
